<template>
    <div class="login-body">
        <div class="bg"></div>
        <div class="login-panel">
            <el-form class="login-register" :model="formData" :rules="rules" ref="formDataRef" @submit.prevent>
                <div class="login-title">团多多</div>
                <!-- 登录 -->
                <div v-if="loginTyoe === 0">
                    <el-form-item prop="userName">
                        <el-input v-model.trim="formData.userName" size="large" maxLength="150" clearable
                            placeholder="用户名/邮箱/手机号"></el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input v-model.trim="formData.password" type="password" size="large" maxLength="20"
                            placeholder="密码"></el-input>
                    </el-form-item>
                </div>
                <!-- 注册 -->
                <div v-else>
                    <el-form-item prop="storeName" v-if="registerType == 0">
                        <el-input v-model.trim="formData.storeName" size="large" maxLength="20" clearable
                            placeholder="店铺名称"></el-input>
                    </el-form-item>
                    <el-form-item prop="contactName" v-if="registerType == 0">
                        <el-input v-model.trim="formData.contactName" size="large" maxLength="20" clearable
                            placeholder="姓名"></el-input>
                    </el-form-item>
                    <el-form-item prop="email">
                        <el-input v-model.trim="formData.email" size="large" maxLength="150" clearable
                            placeholder="邮箱"></el-input>
                    </el-form-item>
                    <el-form-item prop="phone">
                        <el-input v-model.trim="formData.phone" size="large" maxLength="11" clearable
                            placeholder="手机号"></el-input>
                    </el-form-item>
                    <el-form-item prop="code">
                        <div class="send-emali-panel">
                            <el-input v-model.trim="formData.code" size="large"
                                :placeholder="registerNamePla"></el-input>
                            <el-button class="send-mail-btn" type="primary" size="large"
                                @click="emailVerificationCode">获取{{ registerNamePla
                                }}</el-button>
                        </div>
                        <el-popover placement="left" :width="500" trigger="click">
                            <div>
                                <p>1、在垃圾邮箱中查找邮箱验证码</p>
                                <p>2、在邮箱中 头像->设置->反垃圾->白名单->设置邮件地址白名单</p>
                            </div>
                            <template #reference>
                                <span class="a-link" :style="{ 'font-size': '14px' }">未收到邮箱验证码？</span>
                            </template>
                        </el-popover>
                    </el-form-item>
                    <el-form-item prop="registerPassword">
                        <el-input v-model.trim="formData.registerPassword" type="password" size="large" maxLength="20"
                            show-password placeholder="密码"></el-input>
                    </el-form-item>
                    <el-form-item prop="confirmPassword">
                        <el-input v-model.trim="formData.confirmPassword" type="password" size="large" maxLength="20"
                            show-password placeholder="确认密码"></el-input>
                    </el-form-item>
                </div>
                <el-form-item prop="checkCode">
                    <div class="check-code-panel">
                        <el-input v-model.trim="formData.checkCode" clearable size="large" placeholder="验证码"
                            @keyup.enter="doSubmit"></el-input>
                        <img :src="checkCodeUrl" class="check-code" alt="验证码" title="点击刷新验证码"
                            @click="changeCheCode(0)" />
                    </div>
                </el-form-item>
                <!-- 下拉框 -->
                <el-form-item>
                    <div class="rememberme-panel" v-if="loginTyoe === 0">
                        <el-checkbox v-model="formData.rememberMe">记住我</el-checkbox>
                    </div>
                    <div class="no-account">
                        <!-- <a href="javasciprt:void(0)" class="a-link">忘记密码</a> -->
                        <a v-if="loginTyoe === 0 && registerType == null" href="javasciprt:void(0)" class="a-link"
                            @click="resetInformation()">注册商家</a>
                        <a v-else="loginTyoe === 0" href="javasciprt:void(0)" class="a-link"
                            @click="resetInformation()">前往登录</a>
                    </div>
                </el-form-item>
                <!-- 登录按钮 -->
                <el-form-item>
                    <el-button type="primary" class="op-btn" size="large" @click="doSubmit">
                        <span v-if="loginTyoe === 0">登 录</span>
                        <span v-if="loginTyoe === 1">立 即 注 册</span>
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 注册方式选择框 -->
        <el-dialog v-model="dialogFormVisible" width="500">
            <el-form :model="form">
                <el-form-item label="注册方式" :label-width="formLabelWidth">
                    <el-select v-model="form.type" placeholder="请选择注册方式">
                        <el-option label="邮箱注册" value="0" />
                        <!-- <el-option label="手机号注册" value="1" /> -->
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">关闭</el-button>
                    <el-button type="primary" @click="registerTypeSe()">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 获取邮箱验证码 -->
        <Dialog :show="dialogConfig4SendMailCode.show" :title="dialogConfig4SendMailCode.title"
            :buttons="dialogConfig4SendMailCode.buttons" width="500px" :showCancel="false"
            @close="dialogConfig4SendMailCode.show = false">
            <el-form :model="formData4SendMailCode" :rules="rules" ref="formData4SendMailCodeRef" label-width="80px"
                @submit.prevent>
                <el-form-item label="邮箱:">
                    {{ formData4SendMailCode.email }}
                </el-form-item>
                <el-form-item prop="checkCode" label="验证码:">
                    <div class="check-code-panel">
                        <el-input v-model.trim="formData4SendMailCode.checkCode" clearable size="large"
                            placeholder="请输入验证码"></el-input>
                        <img :src="emailCheckCodeUrl" class="check-code" alt="验证码" title="点击刷新验证码"
                            @click="changeCheCode(1)" />
                    </div>
                </el-form-item>
            </el-form>
        </Dialog>
    </div>
</template>
<script setup>
import { ref, reactive, getCurrentInstance, nextTick, watch, onMounted } from 'vue';
import axios from 'axios'
import Dialog from '@/components/Dialog.vue';
import md5 from 'js-md5';
import { useRouter, useRoute } from 'vue-router';


const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();

const api = {
    // 获取验证码
    checkCode: '/api/common/checkCode',
    // 发送邮箱验证码
    sendEmailCode: '/common/sendEmailCode',
    // 商家注册
    register: '/merchant/register',
    // 登录
    login: '/merchant/login',

}

const dialogFormVisible = ref(false);
const form = reactive({
    type: null,
});

// 确认密码比对
const checkRePassword = (rule, value, callback) => {
    if (value !== formData.value.registerPassword) {
        callback(new Error('两次输入密码不一致'));
    } else {
        callback();
    }
};

// 表单数据
const formData = ref({});
// 参数校验
const formDataRef = ref();
const rules = reactive({
    email: [
        { required: true, message: '邮箱不能为空' },
        { validator: proxy.Verfiy.email, message: "请输入正确的邮箱" },
    ],
    password: [
        { required: true, message: '密码不能为空' },
    ],
    storeName: [
        { required: true, message: '店铺名称不能为空' },
    ],
    contactName: [
        { required: true, message: '姓名不能为空' },
    ],
    phone: [
        { required: true, message: '手机号不能为空' },
        { validator: proxy.Verfiy.phone, message: "请输入正确的手机号" },
    ],
    checkCode: [
        { required: true, message: '图形验证码不能为空' },
        { validator: proxy.Verfiy.number, message: "验证码只能是数字" },
    ],
    code: [
        { required: true, message: '邮箱验证码不能为空' },
    ],
    userName: [
        { required: true, message: '账号不能为空' },
    ],
    registerPassword: [
        { required: true, message: '密码不能为空' },
        { validator: proxy.Verfiy.password, message: "密码需 8-18 位，并包含字母和数字" },
    ],
    confirmPassword: [
        { required: true, message: '确认密码不能为空' },
        { validator: checkRePassword, message: '两次输入密码不一致' }
    ],
});

// 监听用户名输入，清空密码
watch(() => formData.value.userName, (newVal, oldVal) => {
    if (oldVal != undefined) {
        formData.value.password = null
    }

})

// 0:登录 1:注册
const loginTyoe = ref(0);
// 注册方式 0:邮箱 1:手机号
const registerType = ref(null);
const registerNamePla = ref(null)
// 登录注册验证码路径
const checkCodeUrl = ref(api.checkCode);
// 获取邮箱验证码的图形验证码路径路径
const emailCheckCodeUrl = ref(api.checkCode);
// 初始化验证码
const changeCheCode = async (value) => {
    try {
        const res = await axios.get(api.checkCode, {
        });
        if (!res) {
            return;
        }
        if (value == 0) {
            checkCodeUrl.value = res.data.data.checkCode;
            proxy.VueCookies.set('checkCodeKey', res.data.data.checkCodeKey, 0);

        } else {
            emailCheckCodeUrl.value = res.data.data.checkCode;
            proxy.VueCookies.set('emailCheckCodeKey', res.data.data.checkCodeKey, 0);
        }
    } catch (err) {
        console.error(err);
    }
};
// 选择注册方式
const registerTypeSe = () => {
    if (form.type == null) {
        proxy.$message.error('请选择注册方式');
        return;
    }
    dialogFormVisible.value = false;
    registerType.value = form.type;
    loginTyoe.value = 1
    if (registerType.value == 0) {
        registerNamePla.value = "邮箱验证码"
    } else {
        registerNamePla.value = "手机验证码"
    }
};

// 获取邮箱验证码按钮
const emailVerificationCode = () => {
    formDataRef.value.validateField('email', (volid) => {
        if (!volid) {
            return;
        }
        dialogConfig4SendMailCode.show = true;
        nextTick(() => {
            changeCheCode(1);
            formData4SendMailCodeRef.value.resetFields();
            formData4SendMailCode.value = {
                email: formData.value.email
            };
        });
    });

}

// 登录、注册信息重置
const resetInformation = () => {
    formData.value = {
    };
    if (formDataRef.value) {
        formDataRef.value.resetFields();
    }
    if (loginTyoe.value === 0) {
        dialogFormVisible.value = true
    } else {
        loginTyoe.value = 0
        registerType.value = null
        initializeRememberMe()
    }
}

// 页面加载完成给表单赋值
const initializeRememberMe = () => {
    const cookieLoginInfo = proxy.VueCookies.get('loginInfo')
    // 判断cookie中是否有登录信息
    if (cookieLoginInfo) {
        formData.value = cookieLoginInfo
    }
}

// 发送邮箱验证码
const formData4SendMailCode = ref({})
const formData4SendMailCodeRef = ref()

const dialogConfig4SendMailCode = reactive({
    show: false,
    title: '发送邮箱验证码',
    buttons: [
        {
            tyep: 'primary',
            text: '发送验证码',
            click: (e) => {
                sendEmailCode()
            }
        }
    ]
});

// 登录或注册
const doSubmit = () => {
    formDataRef.value.validate(async (valid) => {
        if (!valid) {
            return
        }
        const params = Object.assign({}, formData.value)
        params.checkCodeKey = proxy.VueCookies.get('checkCodeKey') == null ? '' : proxy.VueCookies.get('checkCodeKey')
        let url = ''
        let message = ''
        // 登录
        if (loginTyoe.value === 0) {
            url = api.login
            message = '登录成功'
            // 获取cookie中的登录信息
            let cookieLoginInfo = proxy.VueCookies.get('loginInfo')
            // 判断是否记住密码
            let cookiePassword = cookieLoginInfo == null ? '' : cookieLoginInfo.password
            if (params.password != cookiePassword) {
                // 进行md5加密
                params.password = md5(params.password)
            }
            // 判断用户是否勾选记住我
            if (params.rememberMe) {
                const loginInfo = {
                    userName: params.userName,
                    password: params.password,
                    rememberMe: params.rememberMe,
                }
                proxy.VueCookies.set('loginInfo', loginInfo, '7d');
            } else {
                proxy.VueCookies.remove('loginInfo');
            }
        } // 注册 
        else {
            url = api.register
            params.type = form.type
            params.password = params.registerPassword
            message = '注册成功，请登录'
        }
        let result = await proxy.Request({
            url: url,
            params: params,
            errorCallback: () => {
                changeCheCode(0);
            }
        });

        if (!result) {
            return;
        }

        proxy.$message.success(message);
        formDataRef.value.resetFields();
        formData.value = {};
        loginTyoe.value = 0;
        registerType.value = null;

        if (loginTyoe.value === 0) {
            // 登录成功跳转首页
            let redirectUrl = route.query.redirectUrl || '/home';
            if (redirectUrl === "/login" || redirectUrl === "/") {
                redirectUrl = "/home";
            }
            router.push(redirectUrl);
            // 获取当前时间
            const now = new Date();
            // 设置过期时间为 1 天后
            const expireTime = new Date(now.getTime() + 1 * 24 * 60 * 60 * 1000); // 1天 = 24*60*60*1000 毫秒
            result.data.expireTime = expireTime.getTime()
            // 讲用户的登录信息存储到cookie
            proxy.VueCookies.set('userInfo', result.data, '1d');
            proxy.VueCookies.set('token', result.data.token, '1d');
        }
    });
}

// 发送邮箱验证码
const sendEmailCode = () => {
    formData4SendMailCodeRef.value.validate(async (valid) => {
        if (!valid) {
            return
        }
        const params = Object.assign({}, formData4SendMailCode.value)
        params.checkCodeKey = proxy.VueCookies.get('emailCheckCodeKey') == null ? '' : proxy.VueCookies.get('emailCheckCodeKey')
        let result = await proxy.Request({
            url: api.sendEmailCode,
            params: params,
            errorCallback: () => {
                changeCheCode(1);
            }
        });
        if (!result) {
            return;
        }
        proxy.$message.success('邮箱验证码发送成功，请注意查收');
        dialogConfig4SendMailCode.show = false;
    });
}


// 页面加载时调用
onMounted(() => {
    // 获取验证码
    changeCheCode(0);
    // 初始化登录信息
    initializeRememberMe()
});

</script>

<style lang="scss" scoped>
.login-body {
    height: calc(100vh);
    background-size: cover;
    background: url("../assets/login_bg.png") no-repeat center center;
    background-size: cover;
    /* 铺满容器，保持比例，可能裁剪 */
    display: flex;

    .bg {
        flex: 1;
        background-size: cover;
        background-position: center;
        background-size: 800px;
        background-repeat: no-repeat;
        background-image: url("../assets/login_img.png.png");
    }

    .login-panel {
        width: 430px;
        margin-right: 15%;
        margin-top: calc((100vh - 500px) / 2);

        .login-register {
            padding: 25px;
            background: #fff;
            border-radius: 5px;

            .login-title {
                text-align: center;
                font-size: 18px;
                font-weight: bold;
                margin-bottom: 20px;
            }

            .send-emali-panel {
                display: flex;
                width: 100%;
                justify-content: space-between;

                .send-mail-btn {
                    margin-left: 5px;
                }
            }

            .rememberme-panel {
                width: 100%;
            }

            .no-account {
                width: 100%;
                display: flex;
                justify-content: space-between;
            }

            .op-btn {
                width: 100%;
            }
        }
    }

    .check-code-panel {
        width: 100%;
        display: flex;

        .check-code {
            width: 100px;
            height: 40px;
            margin-left: 5px;
            cursor: pointer;
        }
    }

    .login-btn-qq {
        margin-top: 20px;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;

        img {
            cursor: pointer;
            margin-left: 10px;
            width: 20px;
        }
    }
}
</style>